package css.sword.util;

import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.codec.TiffImage;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PdfUtils {

    private static int interval=-5;

    public static void waterMarkerText(PdfReader reader, OutputStream outputstream, String text) throws
            DocumentException, IOException {

        PdfStamper stamper = null;

            stamper = new PdfStamper(reader, outputstream);
            BaseFont bfSun=BaseFont.createFont("/com/itextpdf/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.1f);
            gs.setStrokeOpacity(0.1f);
            int total = reader.getNumberOfPages() + 1;
            
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(text);

            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();

//            for(int m=0;m<4;m++){
//                text+="      "+text;
//            }

            textW = metrics.stringWidth(text);

            PdfContentByte under;
            
            java.awt.Font pjf = getFont(text);
            
            // 生成水印图片流
            BufferedImage bufferedImage= getTextToImage(text, pjf, (int)(textW*6.618), textH+60);
            Image image = Image.getInstance(bufferedImage, null);
            
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);

//                under.saveState();
                under.setGState(gs);
//                under.beginText();
//                under.setFontAndSize(bfSun, 18);
//                under.setColorFill(new BaseColor(Color.GRAY.getRGB()));

                int m=0;
                int height=0;
                // 水印文字成30度角倾斜
                //你可以随心所欲的改你自己想要的角度

                Rectangle pageSize = reader.getPageSize(i);
            	float pageHeight = pageSize.getHeight();// 获取当前页的高
                float pageWidth = pageSize.getWidth();// 获取当前页的宽
                //System.out.println(pageHeight);
                //System.out.println(pageWidth);
                if(pageHeight>=pageWidth) {// 标准文档
                	image.setRotation(-20);// 旋转 弧度
                    image.setRotationDegrees(55);// 旋转角度
                	image.setAbsolutePosition(80, 150);
                } else {// 发票
                	image.setRotation(-20);// 旋转 弧度
                    image.setRotationDegrees(30);// 旋转角度
                	image.setAbsolutePosition(4, 4);
                }
                
                under.addImage(image);// 图片水印

//                for (height = interval + textH; height < pageRect.getHeight();
//                     height = height + (int)(textH * 5.618)) {
//                     m++;
//                     if(m%2==0) continue;
//                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
//                         width = width + (int)(textW * 1.618)) {
//                       // System.out.println(height - textH);
//                        if(height<=pageRect.getHeight()){
//                            /*under.showTextAligned(Element.ALIGN_LEFT
//                                    , text, width - textW,
//                                    height - textH, 45);//文字水印*/
//
//                            image.setAbsolutePosition(width - textW, height - textH); // 水印坐标
//                            under.addImage(image);// 图片水印
//                        }
//
//                    }
//
//                }
//                for (int width = 108; width < pageRect.getWidth();
//                     width = width +108) {
//                        under.showTextAligned(Element.ALIGN_LEFT
//                                , text, width,
//                                0, 45);
//                }

                // 添加水印文字
//                under.endText();
                  under.stroke();
                //System.out.println("完毕");
            }
            if(stamper!=null)
                stamper.close();
            reader.close();

    }
    
    /**
              *  判断字符串是否包含数字
     * @param company
     * @return
     */
    private static boolean isContainNumber(String company) {
        Pattern p = Pattern.compile("[0-9]");
        Matcher m = p.matcher(company);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
               * 根据文字长度设置字体大小
     *@name    中文名称
     *@description 相关说明
     *@time    创建时间:2018年12月10日下午5:09:57
     *@param text
     *@return
     *@author   兰建青
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static java.awt.Font getFont(String text) {
    	//System.out.println(text.length());
        java.awt.Font font = null;//new java.awt.Font("华文中宋", java.awt.Font.BOLD, 68);
        if(text.length()==45){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 16);
        }else if(text.length()==44){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 17);
        }else if(text.length()==43){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 17);
        }else if(text.length()==42){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 17);
        }else if(text.length()==41){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 18);
        }else if(text.length()==40){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 18);
        }else if(text.length()==39){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 19);
        }else if(text.length()==38){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 19);
        }else if(text.length()==37){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 20);
        }else if(text.length()==36){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 21);
        }else if(text.length()==35){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 21);
        }else if(text.length()==34){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 22);
        }else if(text.length()==33){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 23);
        }else if(text.length()==32){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 24);
        }else if(text.length()==31){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 25);
        }else if(text.length()==30){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 26);
        }else if(text.length()==29){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 27);
        }else if(text.length()==28){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 28);
        }else if(text.length()==27){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 30);
        }else if(text.length()==26){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 34);
        }else if(text.length()==25){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 36);
        }else if(text.length()==24){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 38);
        }else if(text.length()==23){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 40);
        }else if(text.length()==22){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 44);
        }else if(text.length()==21){
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 48);
        }else{
            font = new java.awt.Font("仿宋", java.awt.Font.BOLD, 56);
        }
        return font;
    }

    /**
     * 将文字转成图片
     *@name    中文名称
     *@description 相关说明
     *@time    创建时间:2018年12月5日下午1:17:25
     *@param text 要转换成图片的文字
     *@param font 字体样式
     *@param width 文字图片宽度
     *@param height 文字图片高度
     *@return BufferedImage
     *@author   兰建青
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static BufferedImage getTextToImage(String text, java.awt.Font font, Integer width, Integer height) {
        // 创建图片  
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        
        // 透明背景
        bufferedImage = graphics.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        graphics=bufferedImage.createGraphics(); 
        
        graphics.setClip(0, 0, width, height);  
       // java.awt.Color color = new java.awt.Color(Color.gray);
        graphics.setColor(Color.gray);
        graphics.setFont(font);// 设置画笔字体  
        
        /** 用于获得垂直居中y */  
        java.awt.Rectangle rectangle = graphics.getClipBounds();
        FontMetrics fontMetrics = graphics.getFontMetrics(font);
        int ascent = fontMetrics.getAscent();
        int descent = fontMetrics.getDescent();
        int y = (rectangle.height - (ascent + descent)) / 2 + ascent;
       // for (int i = 0; i < 6; i++) {// 256 340 0 680
            graphics.drawString(text,  0, y);// 画出字符串
        //}
        graphics.dispose();

//         try {
//            ImageIO.write(bufferedImage, "png", new File("C:\\\\Users\\\\12555\\\\Desktop\\\\1.png"));// 保存图片
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return bufferedImage;
    }

    /**
     * 修改pdf属性
     *@name    中文名称
     *@description 相关说明
     *@time    创建时间:2018年10月25日下午3:19:38
     *@param souceFilePath 源文件的地址
     *@param targetFilePath 修改后的目标文件路劲
     *@param title 标头信息modifyPdfAttribute
     *@param subject 主题信息
     *@param keywords 关键字
     *@throws IOException
     *@throws DocumentException
     *@author   祥保玉
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */

    public static void modifyPdfAttribute(String souceFilePath,String targetFilePath,String title,String subject,String keywords) throws IOException, DocumentException {
        String srcFile = souceFilePath;//要修改的pdf文件
        PdfReader reader = new PdfReader(srcFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(targetFilePath)));
        Map<String, String> moreInfo = new HashMap<String,String>();
        moreInfo.put("Title", title);
        moreInfo.put("Subject", subject);
        moreInfo.put("Keywords", keywords);
        stamper.setMoreInfo(moreInfo);
//        int total = reader.getNumberOfPages() + 1;
//        PdfContentByte content;
//
//        for (int i = 1; i < total; i++)
//        {
//            content = stamper.getUnderContent(i);
//            content.beginText();
//            content.endText();
//        }
        stamper.close();
    }



    public static void text2pdf(InputStream in,OutputStream out) throws DocumentException, IOException{
        BaseFont bfSun=BaseFont.createFont("/com/itextpdf/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfSun, 12, Font.NORMAL);
        Rectangle rect = new Rectangle(PageSize.A4.rotate());
        Document doc = new Document(rect);
        PdfWriter writer = PdfWriter.getInstance(doc, out);

        doc.open();

        try(BufferedReader read = new BufferedReader(new InputStreamReader(in,"GB2312"))){
            while(read.ready()){
                String a=read.readLine();
                //System.out.println(a);
                doc.add(new Paragraph(a,fontChinese));
            }
        }
        doc.close();
    }

    public static void jpg2pdf(String srcFilePath,OutputStream fos) throws DocumentException, IOException {
        // BaseFont bfSun=BaseFont.createFont("/com/itextpdf/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        BufferedImage img = ImageIO.read(new File(srcFilePath));
        Document doc = new Document(null, 0, 0, 0, 0);

        doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
        Image image = Image.getInstance(srcFilePath);
        PdfWriter.getInstance(doc, fos);
        doc.open();
        doc.add(image);
        doc.close();
    }


    public static void mergeRed(InputStream mergedPdf, byte[] redPdf, OutputStream out) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(mergedPdf);
        PdfStamper stamp = new PdfStamper(reader,out);
        // 拿到第一页的上部内容部分

        PdfContentByte over = stamp.getOverContent(1);
        // 增加内容

        // 从现有的别的pdf合并过来
        PdfReader reader2 = new PdfReader(redPdf);
//        System.out.println(reader2.getPageSize(1).equals(PageSize.A3));
//        System.out.println(reader2.getPageSize(1));
//        System.out.println(PageSize.A3);
        over.addTemplate(stamp.getImportedPage(reader2, 1), 1, 0, 0, 1, 0, 0);
//        int n = reader2.getNumberOfPages();
////        System.out.println("page"+n);
//        if(n>1){
//            // 写上内容
//            for(int i=2;i<=n;i++){
//               // System.out.println(i+"eeeee"+stamp.getImportedPage(reader2, i).getBoundingBox().getWidth());
//                stamp.insertPage(i, stamp.getImportedPage(reader2, i).getBoundingBox());
//                over = stamp.getUnderContent(i);
//                over.addTemplate(stamp.getImportedPage(reader2, i), 1, 0, 0, 1, 0, 0);
//            }
//        }
//        System.out.println(reader2.getNumberOfPages());
//        System.out.println(reader.getNumberOfPages());
        reader.selectPages("1-"+reader.getNumberOfPages());
        stamp.close();
        reader2.close();
        reader.close();
    }

//    public static void deletePage(String srcFile, OutputStream out) throws IOException, DocumentException {
//
//        PdfReader reader = new PdfReader(srcFile);// 读取pdf
//        reader.r
//        reader.selectPages("1,3");// 选择页数
//        stamp = new PdfStamper(reader, out);// 输出
//        stamp.close();
//        reader.close();
//
//
//    }



    public static void main(String[] args) throws FileNotFoundException, DocumentException {
        /*Document document = new Document(PageSize.A4.rotate());
        PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream("C:\\Users\\12555\\Desktop\\demo.pdf"));
        // 设置用户密码, 所有者密码,用户权限,所有者权限
        pdfWriter.setEncryption("userpassword".getBytes(), "ownerPassword".getBytes(),  PdfWriter.ALLOW_SCREENREADERS, PdfWriter.ENCRYPTION_AES_128);
        // 打开文档
        document.open();
        // 创建第一页（如果只有一页的话，这一步可以省略）
        document.newPage();
        // 加入文档内容
        document.add(new Paragraph("my first pdf demo"));
        // 关闭文档
        document.close();
        pdfWriter.close();*/

        //File file=new File("C:\\Users\\12555\\Desktop\\hytz_市政府11届10次常务会议-LJW.pdf");
        //InputStream in = new FileInputStream(file);
        //OutputStream out = new FileOutputStream("C:\\\\Users\\12555\\Desktop\\WATERMARK.PDF");
        
        /*File file=new File("C:\\\\Users\\\\12555\\\\Desktop\\\\尚硅谷JavaEE技术之MyBatisPlus.pdf");
        InputStream in = new FileInputStream(file);
        OutputStream out = new FileOutputStream("C:\\\\Users\\\\12555\\\\Desktop\\\\尚硅谷JavaEE技术之MyBatisPlusaaaaa.pdf");
        try {
            waterMarkerText(new PdfReader(in),out,"深圳市科技创新管理局");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    	
        File file=new File("E:\\发票.pdf");
        InputStream in = new FileInputStream(file);
        OutputStream out = new FileOutputStream("E:\\发票-有水印.pdf");
        try {
            waterMarkerText(new PdfReader(in),out,"领公 2018-12-12 12:12:12");// 赖镇先 2018-12-12 12:12:12
            																				//叶凡 2018-12-12 12:12:12
            																				//欧阳娜娜 2018-12-12 12:12:12   
            																				//中共深圳市委党的群众路线教育实践活动领导小组办公室
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        /*BufferedImage bufferedImage= getTextToImage("深圳市科技创新管理局", new java.awt.Font("仿宋_GB2312", java.awt.Font.PLAIN, 14), "深圳市科技创新管理局".length()*10, 36);
        
        File imgFile=new File("e://1.png");  
        try  
        {  
            ImageIO.write(bufferedImage, "PNG", imgFile);  
        } catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        System.out.println("生成完成");*/

    }

    public static void encryptPdf(String sourcePdf,String targetPdf,String userPassword,String ownerPassword) throws DocumentException, IOException {
        PdfReader reader = new PdfReader(sourcePdf);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPdf));
        stamper.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_MODIFY_CONTENTS, true);

        stamper.close();
        reader.close();
    }

    /**
     * 调用wps的com接口实现word文件转pdf文件
     * @param wordFilePath word文件路径
     * @param pdfFilePath pdf文件路径
     * @return
     */
    public  static boolean wps_word2pdf(String wordFilePath,String pdfFilePath){
        Long startTime=System.currentTimeMillis();
        File pdfFile = new File(pdfFilePath);
        ActiveXComponent wps = null;
        ComThread.InitSTA();
        Dispatch doc = null;
        System.out.println(wordFilePath);
        System.out.println(pdfFilePath);
        try {
            wps = new ActiveXComponent("kwps.application");
            wps.setProperty("visible", new Variant(true));
            Dispatch docs = wps.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", wordFilePath, false, true).toDispatch();
            if(pdfFile.exists()){
                pdfFile.delete();
            }
            Dispatch.call(doc, "SaveAs", pdfFilePath, 17);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            Dispatch.call(doc, "Close", false);
            if (wps != null) {
                wps.invoke("Quit", new Variant[]{});
            }
            System.out.println(System.currentTimeMillis()-startTime+"转版耗时");
            ComThread.Release();
        }
        return true;
    }

    /**
     * 接受修订  清除痕迹
     * @param docFilePath word文件路径
     * @return
     */
    public static boolean acceptAllRevisions(String docFilePath){
        boolean flag = false;
        try {
            com.aspose.words.Document doc = new com.aspose.words.Document(docFilePath);
            doc.acceptAllRevisions();
            doc.save(docFilePath);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("清除痕迹异常 ："+e.getMessage());
            return false;
        }
        return flag;
    }
//    /**
//     * word文件套红操作
//     * @param wordFile	word文件
//     * @param redFile	红头文件
//     * @param pdfFile	即将保存的pdf文件
//     * @return
//     */
//    public static HTTPFile wordAddRed(HTTPFile wordFile,HTTPFile redFile,HTTPFileImport pdfFile){
//        return wordAddRed(wordFile,redFile,pdfFile,false);
//    }
//
//    /**
//     * word文件套红操作
//     * @param wordFile	word文件
//     * @param redFile	红头文件
//     * @param pdfFile	即将保存的pdf文件
//     * @return
//     */
//    public static HTTPFile wordAddRed(HTTPFile wordFile,HTTPFile redFile,HTTPFileImport pdfFile,boolean acceptAllRevisions){
//
//        String wordFilePath=wordFile.getFilePath();
//        String pdfFileName=wordFile.getFileName().substring(0, wordFile.getFileName().lastIndexOf("."))+".pdf";
//        String pdfFilePath=pdfFile.getImportFilePath(pdfFileName);
//        if(acceptAllRevisions){
//            acceptAllRevisions(wordFilePath);
//        }
//        //word文件转pdf
//        word2pdf(wordFilePath,pdfFilePath);
//        WordConvertProvider wcp=new WordConvertProvider();
//        try {
//            wcp.coverHeadPdf(pdfFilePath, pdfFilePath, redFile.getFilePath());
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        return pdfFile.saveImportFile();
//    }

    public static boolean wps_xml2word(String wordFilePath,String newFilePath){
        File pdfFile = new File(newFilePath+".tmp");
        ActiveXComponent wps = null;
        Dispatch doc = null;
        try {
            wps = new ActiveXComponent("kwps.application");
            wps.setProperty("visible", new Variant(false));
            Dispatch docs = wps.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", wordFilePath, false, true).toDispatch();
            if(pdfFile.exists()){
                pdfFile.delete();
            }
            Dispatch.call(doc, "SaveAs", newFilePath, 0);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            Dispatch.call(doc, "Close", false);
            if (wps != null) {
                wps.invoke("Quit", new Variant[]{});
            }
            if(pdfFile.exists()){
                File newPdfFile=new File(newFilePath);
                if(newPdfFile.exists())
                    newPdfFile.delete();
                pdfFile.renameTo(newPdfFile);
            }
        }
        return true;
    }

    public  static boolean wps_excel2pdf(String wordFilePath,String pdfFilePath){
        File pdfFile = new File(pdfFilePath);
        ActiveXComponent wps = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            wps = new ActiveXComponent("KET.Application");
            wps.setProperty("visible", new Variant(false));
            Dispatch docs = wps.getProperty("Workbooks").toDispatch();
            doc = Dispatch.call(docs, "Open", wordFilePath,false,true).toDispatch();
            Dispatch sheets = Dispatch.get((Dispatch) doc, "Sheets")
                    .toDispatch();
            int count = Dispatch.get(sheets, "Count").getInt();
//     System.out.println(count);
            for (int j = 1; j <=count; j++) {
                Dispatch sheet = Dispatch.invoke(sheets, "Item",
                        Dispatch.Get, new Object[]{new Integer(j)},
                        new int[1]).toDispatch();
                Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch();
                Dispatch.put(pageSetup, "Orientation", 2);
            }
            if(pdfFile.exists()){
                pdfFile.delete();
            }
           // System.out.println(wordFilePath);
            Dispatch.call( doc, "ExportAsFixedFormat",0,pdfFile.getAbsolutePath());
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            Dispatch.call(doc, "Close", false);
            if (wps != null) {
                wps.invoke("Quit", new Variant[]{});
            }
            ComThread.Release();
        }
        return true;
    }



    public static void addWaterMark(String filepath,String username) {
        try {
            String waterMarkStr = getWaterMarkString(username);
            ComThread.InitSTA();
            ActiveXComponent wordApp = new ActiveXComponent("kwps.application");// 初始化word应用程序，初始化表格是：Excel.Application
            wordApp.setProperty("Visible", new Variant(false));// 配置启动word时是显示执行还是隐式执行
            Dispatch wordDocs = wordApp.getProperty("Documents").toDispatch();// 获取word所有文档对象
            Dispatch aDoc = Dispatch.call(wordDocs, "Open", new Variant(filepath)).toDispatch();// docPath要打开的文档的详细地址
            Dispatch docSelection = Dispatch.get(wordApp, "Selection").toDispatch();// 获得该文档对象，并返回
            Dispatch activeWindow = wordApp.getProperty("ActiveWindow").toDispatch();// 取得活动窗体对象
            Dispatch activePane = Dispatch.get(activeWindow, "ActivePane").toDispatch();// 活动窗格
            Dispatch view = Dispatch.get(activePane, "View").toDispatch();// 视窗对象
            Dispatch.put(view, "SeekView", new Variant(9));// 打开页眉，值为9，页脚值为10

            Dispatch headerfooter = Dispatch.get(docSelection, "HeaderFooter").toDispatch();// 获取页眉和页脚
            Dispatch shapes = Dispatch.get(headerfooter, "Shapes").toDispatch();// 获取水印图形对象

            Dispatch temp = Dispatch.get(activeWindow, "Selection").toDispatch();
            Dispatch.call(temp, "ClearFormatting");
            temp = wordApp.getProperty("ActiveDocument").toDispatch();
            temp = Dispatch.get(temp, "PageSetup").toDispatch();
            Dispatch.put(temp, "HeaderDistance", new Variant(0));//
            Dispatch.put(temp, "FooterDistance", new Variant(0));//

            /**
             * 插入文字，并转为图片： 操作对象、方法、艺术字格式[0白色、1黑左下右上，2黑中上两下、3黑中小两大、4黑竖排、5黑中下两上]
             * 水印内容、字体、字体大小、字体是否粗体、字体是否斜体 左边距、上边距
             */
            Dispatch selection = Dispatch.call(shapes, "AddTextEffect", new Variant(0), waterMarkStr, "仿宋_GB2312",
                    new Variant(16), new Variant(true), new Variant(false), new Variant(0), new Variant(0))
                    .toDispatch();

            // 选中当前文档水印
            Dispatch.call(selection, "Select");
            Dispatch shapeRange = Dispatch.get(docSelection, "ShapeRange").toDispatch();

            /**
             * 设置水印透明度和颜色
             */
            Dispatch.put(shapeRange, "Name", "PowerPlusWaterMarkObject6");
            Dispatch textEffect = Dispatch.get(shapeRange, "TextEffect").toDispatch();
            Dispatch.put(textEffect, "NormalizedHeight", new Boolean(false));

            Dispatch line = Dispatch.get(shapeRange, "Line").toDispatch();
            Dispatch.put(line, "Visible", new Boolean(false));

            Dispatch fill = Dispatch.get(shapeRange, "Fill").toDispatch();
            Dispatch.put(fill, "Visible", new Boolean(true));

            Dispatch foreColor = Dispatch.get(fill, "ForeColor").toDispatch();
            Dispatch.put(foreColor, "RGB", "14474460");// 设置水印颜色 220
            // Dispatch.put(foreColor, "RGB", new Variant(10));// 设置水印颜色
            Dispatch.call(fill, "Solid");

            /**
             * 设置水印旋转角度、水印大小
             */
            Dispatch.put(shapeRange, "Rotation", new Variant(-45));// 旋转角度
            Dispatch.put(shapeRange, "Height", new Variant(704));// 高
            Dispatch.put(shapeRange, "Width", new Variant(1024));// 宽
            Dispatch.put(shapeRange, "Top", new Variant(25));
            Dispatch.put(shapeRange, "Left", new Variant(-200));

            Dispatch.put(view, "SeekView", new Variant(0));// 0表示恢复视图;
            Dispatch.call(aDoc, "Save");// 保存
            Dispatch.call(aDoc, "Close", new Variant(0));// 关闭
            wordApp.invoke("Quit", new Variant[] {});// 关闭word文件
            ComThread.Release();// 释放com线程。根据jacob的帮助文档，com的线程回收不由java的垃圾回收器处理
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getWaterMarkString(String username) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
        String datetime = sdf.format(new Date());
        // 一行内容
        StringBuffer strbuf = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            strbuf.append(username + datetime + "          ");
        }
        String line = strbuf.toString();
        // 循环5行
        StringBuffer strbufresult = new StringBuffer();
        for (int i = 1; i < 54; i++) {
            strbufresult.append("\n");
            if (i % 9 == 0) {
                strbufresult.append(line + "\n");
            }
        }
        return strbufresult.toString();
    }

    public static void tifToPdf(String tifFilepath, OutputStream out) throws Exception {
        Document docment = new Document(PageSize.LETTER, 0, 0, 0, 0);// 创建一个文档对象
        PdfWriter pdfWriter = PdfWriter.getInstance(docment, out);
        pdfWriter.setStrictImageSequence(true);
        int tifFilePageCount = 0;// tif文件页数
        File tifFile = new File(tifFilepath);
        InputStream tifFileInputStream  = new FileInputStream(tifFile);
        RandomAccessFileOrArray randomAccessFile = new RandomAccessFileOrArray(tifFileInputStream);
        tifFilePageCount = TiffImage.getNumberOfPages(randomAccessFile);
        if (null != tifFileInputStream) {
            tifFileInputStream.close();
        }
        for (int pageNumber = 1; pageNumber <= tifFilePageCount; pageNumber++) {
            // 将tif文件读取成图片
            Image tifImg = TiffImage.getTiffImage(randomAccessFile, pageNumber);
            if (null == tifImg) {
                throw new Exception("读取tif文件失败");
            }
            // 设置首页tif图片的大小
            Rectangle firstpageSize = new Rectangle(tifImg.getWidth(), tifImg.getHeight());
            docment.setPageSize(firstpageSize);
            docment.open();// 打开文档对象
            // 设置图片大小
            docment.setPageSize(new Rectangle(tifImg.getWidth(), tifImg.getHeight()));
            tifImg.setAbsolutePosition(0, 0);// 设置图像位置
            tifImg.setAlignment(Image.ALIGN_CENTER);// 设置图像的对齐方式(居中)。
            docment.add(tifImg);// 加载tif图片
            docment.newPage();
        }
        if (null != randomAccessFile) {
            randomAccessFile.close();
        }
        // 关闭文档对象，释放资源
        if (null != docment) {
            docment.close();
        }

    }

//复制jacob.jar包到项目lib到下,对应本地操作系统复制jacob-1.19-x64.dll/jacob-1.19-x86.dll到系统盘:/Windows/System32下
// 格式大全:前缀对应以下方法的fmt值
// 0:Microsoft Word 97 - 2003 文档 (.doc)
// 1:Microsoft Word 97 - 2003 模板 (.dot)
// 2:文本文档 (.txt)
// 3:文本文档 (.txt)
// 4:文本文档 (.txt)
// 5:文本文档 (.txt)
// 6:RTF 格式 (.rtf)
// 7:文本文档 (.txt)
// 8:HTML 文档 (.htm)(带文件夹)
// 9:MHTML 文档 (.mht)(单文件)
// 10:MHTML 文档 (.mht)(单文件)
// 11:XML 文档 (.xml)
// 12:Microsoft Word 文档 (.docx)
// 13:Microsoft Word 启用宏的文档 (.docm)
// 14:Microsoft Word 模板 (.dotx)
// 15:Microsoft Word 启用宏的模板 (.dotm)
// 16:Microsoft Word 文档 (.docx)
// 17:PDF 文件 (.pdf)
// 18:XPS 文档 (.xps)
// 19:XML 文档 (.xml)
// 20:XML 文档 (.xml)
// 21:XML 文档 (.xml)
// 22:XML 文档 (.xml)
// 23:OpenDocument 文本 (.odt)
// 24:WTF 文件 (.wtf)
//        public static File convertDocFmt(String srcPath, String descPath, int fmt) throws Exception {
//            // 实例化ComThread线程与ActiveXComponent
//            ComThread.InitSTA();
//            ActiveXComponent app = new ActiveXComponent("Word.Application");
//            try {
//                // 文档隐藏时进行应用操作
//                app.setProperty("Visible", new Variant(false));
//                // 实例化模板Document对象
//                Dispatch document = app.getProperty("Documents").toDispatch();
//                // 打开Document进行另存为操作
//                Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,
//                        new Object[] { srcPath, new Variant(true), new Variant(false) }, new int[1]).toDispatch();
//                Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { descPath, new Variant(fmt) }, new int[1]);
//                Dispatch.call(doc, "Close", new Variant(false));
//                return new File(descPath);
//            } catch (Exception e) {
//                throw e;
//            } finally {
//                // 释放线程与ActiveXComponent
//                app.invoke("Quit", new Variant[] {});
//                ComThread.Release();
//            }
//        }

}
